package com.study.modules.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.study.common.utils.JWTUtils;
import com.study.common.utils.R;
import com.study.modules.sys.model.dto.SysUserDTO;
import com.study.modules.sys.model.entity.SysUser;
import com.study.modules.sys.service.SysUserRoleService;
import com.study.modules.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 用户
 *
 * @Author Mr.Du
 * @Date 2021/10/16 8:59
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Autowired
    private JWTUtils jwtUtils;


    /**
     * 登录
     *
     * @param loginName 用户名
     * @param password  密码
     * @return token
     */
    @PostMapping("/login")
    public R login(@RequestParam("loginName") String loginName, @RequestParam("password") String password) {
        //根据用户名查询用户
        SysUser dbUser = userService.selectPsdSaltByLoginName(loginName);
        //数据库密码和登录密码加密比较
        if (!dbUser.getPassword().equals(new Sha256Hash(password, dbUser.getSalt()).toHex())) {
            return R.error("密码不正确");
        }
        String token = jwtUtils.generateToken(dbUser.getId());
        long expire = jwtUtils.getExpire();
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", expire);
        return R.ok(map);
    }

    /**
     * 退出系统
     * @return true
     */
    @PostMapping("/loginOut")
    public R loginOut(){
        SecurityUtils.getSubject().logout();
        return R.ok("退出成功");
    }

    /**
     * 查询用户详情
     * @param userId 用户id
     * @return SysUserDTO
     */
    @GetMapping("/{userId}")
    @RequiresPermissions("sys:user:info")
    public R selectUserById(@PathVariable("userId") Long userId) {
        return R.ok().setData(userService.selectUserInfo(userId));
    }

    /**
     * 获取用户列表
     *
     * @return 列表
     */
    @GetMapping("/getUserList")
    @RequiresPermissions("sys:user:list")
    public R getUserList(@RequestParam(value = "status", required = false) String status, Page<SysUser> page) {
        return R.ok().setData(userService.selectUserList(status,page));
    }

    /**
     * 新增用户
     *
     * @param user 用户信息
     * @return success
     */
    @PostMapping("/insert")
    @RequiresPermissions("sys:user:add")
    public R insert(@RequestBody @Validated SysUserDTO user) {
        user.setCreateId(getUserId());
        userService.insert(user);
        return R.ok();
    }

    /**
     * 获取用户权限
     *
     * @return list
     */
    @GetMapping("/getPermission")
    @RequiresPermissions("sys:user:perms")
    public R getPermissionsList() {
        Set<String> permsList = userRoleService.selectUserRole(getUserId());
        return R.ok().setData(permsList);
    }

    /**
     * 跟新别的用户的基础信息
     *
     * @param user 用户信息
     * @return success
     */
    @PutMapping("/updateByWeb")
    @RequiresPermissions("sys:user:update")
    public R updateByWeb(@RequestBody @Validated SysUserDTO user) {
        return R.ok().setData(userService.updateByWeb(user,getUserId()));
    }

    /**
     * 管理员重置用户密码
     * @param userId 用户id
     * @return true
     */
    @PutMapping("/resetPassword/{userId}")
    @RequiresPermissions("sys:user:resetPsd")
    public R resetPassword(@PathVariable("userId") Long userId){
        return R.ok().setData(userService.resetPassword(userId,getUserId()));
    }

    /**
     * 用户修改密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return true
     */
    @PutMapping("updatePsd")
    @RequiresPermissions("sys:user:updatePsd")
    public R updatePsd(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword") String newPassword) {
        return R.ok().setData(userService.updatePsd(oldPassword, newPassword, getUserId()));
    }

    /**
     * 用户禁用
     *
     * @param userId 用户id
     * @param status 要变成的状态号
     * @return true
     */
    @PutMapping("/{userId}/{status}")
    @RequiresPermissions("sys:user:disable")
    public R disableUser(@PathVariable("userId") Long userId, @PathVariable("status") Integer status) {
        return R.ok().setData(userService.disableUser(userId, status, getUserId()));
    }

    /**
     * 删除用户
     *
     * @param userId 用户Id
     * @return true
     */
    @DeleteMapping("/{userId}")
    public R delete(@PathVariable("userId") Long userId) {
        return R.ok().setData(userService.delete(userId, getUserId()));
    }

}
